<template>
    <div class="login-wrapper">
        <div class="modal">
            <el-form ref="userForm" :model="user" hide-required-asterisk status-icon :rules="rules">
                <div class="title">火星</div>
                <el-form-item prop="username" required>
                    <el-input v-model="user.username" type="text" prefix-icon="user"></el-input>
                </el-form-item>
                <el-form-item prop="password" required>
                    <el-input v-model="user.password" type="password" prefix-icon="view"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="clickLogin" type="primary" class="btn-login">登录
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import type { FormInstance, FormRules } from 'element-plus'
import { login } from "@/api/index"

// 获取表单ref
const userForm = ref<FormInstance>()

// 登录变量
const user = reactive({
    username: '',
    password: ''
})

// 验证
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入用户', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ]
})

const route = useRouter()
const store = useStore()

// 登录
const clickLogin = () => {
    console.log("点击登录", userForm)
    userForm.value!.validate((valid: boolean) => {
        if (valid) {
            login(user).then((res: any) => {
                console.log('返回参数', res)
                store.commit('saveUserInfo', res)
                store.dispatch("loadAsyncRoutes")
                route.push('/')
            })
        }
    })
}

</script>

<style lang='scss' scoped>
.login-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f9fcff;
    width: 100vw;
    height: 100vh;

    .modal {
        width: 500px;
        padding: 50px;
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0px 0px 10px 3px #c7c9cb4d;

        .title {
            font-size: 50px;
            line-height: 1.5;
            text-align: center;
            margin-bottom: 30px;
        }

        .btn-login {
            width: 100%;
        }
    }
}
</style>